# -*- coding: utf-8 -*-
"""
Created on Sun May  9 14:14:15 2021

@author: Hu Yue
@email: hhhuyue@gmail.com

Note:
"""


import pandas as pd
import numpy as np
import scipy.stats as si

def EMA(price,decay_rate,time_period):
    
    # 计算收益率
    #ret = (price[1:] - price[:-1])/price[:-1]
    #ret = (price/price.shift(1))-1
    
    ret = np.log(price/price.shift(1))
    square_ret = ret**2
    
    # 计算每日的权重
    times = np.argsort(-1*np.arange(0,60))
    weight = (1-decay_rate)*(decay_rate**times)
    
    var =np.zeros(len(ret))
    for i in range(time_period,len(ret)):
        var[i] = np.sum(square_ret.iloc[i-time_period:i]*weight)*252
    vol = np.sqrt(var)
    
    return vol

# 计算希腊值
def get_option_greek(S,K,r,sigma,T,cp_type):
    
    if cp_type == "C":
        n = 1
    else:
        n = -1
    
    d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma ** np.sqrt(T))
    d2 = d1 - sigma * np.sqrt(T)
    delta = n * si.norm.cdf(n * d1)
    gamma = si.norm.pdf(d1) / (S * sigma * np.sqrt(T))
    
    theta = (-1 * (S * si.norm.pdf(d1) * sigma) / (2 * np.sqrt(T)) - n * r * K * np.exp(
            -r * T) * si.norm.cdf(n * d2)) / 252
    
    vega = (S * si.norm.pdf(d1) * np.sqrt(T)) / 100


    greek ={"delta":delta,
            "gamma":gamma,
            "theta":theta,
            "vega":vega}

    return greek

# 计算价格
def get_option_price(S,K,r,sigma,T,cp_type):
    
        q = 0

        if cp_type == "C":
            n = 1
        else:
            n = -1

        d1 = (np.log(S / K) + (r + 0.5 * sigma ** 2) * T) / (sigma ** np.sqrt(T))
        d2 = d1 - sigma * np.sqrt(T)
        
        option_price = n * (S * np.exp(-q * T) * si.norm.cdf(d1*n) - K * np.exp(-r * T) * si.norm.cdf(d2*n))

        return option_price
    

if __name__=="__main__":
    
    stock_price = pd.read_feather("data/stockprice.feather")
    stock_price = stock_price[stock_price['SecurityID']==106445]

    decay_rate =0.96
    time_period = 60
    
    vol = EMA(stock_price['Price'],decay_rate,time_period)
    option_greeks = get_option_greek(2200,2300,0.0335,0.2,0.25,"C")
    adj_delta = option_greeks['delta']
    
    option_price = get_option_price(2200,2300,0.0335,0.2,0.25,"C")